<template>
  <div class="quote-record-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form 
        :model="searchForm" 
        :inline="true" 
        class="search-form"
        label-width="100px"
      >
        <el-form-item label="客户代码">
          <el-select
            v-model="searchForm.customerCode"
            placeholder="输入客户代码或名称搜索"
            clearable
            filterable
            remote
            reserve-keyword
            :remote-method="handleCustomerSearch"
            :loading="customerLoading"
            style="width: 180px"
          >
            <el-option 
              v-for="customer in customerOptions" 
              :key="customer.value" 
              :label="`${customer.value} - ${customer.label}`"
              :value="customer.value" 
            >
              <span style="float: left">{{ customer.value }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ customer.label }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="产品名称">
          <el-input
            v-model="searchForm.productName"
            placeholder="请输入产品名称"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        
        <el-form-item label="物料编码">
          <el-input
            v-model="searchForm.materialCode"
            placeholder="请输入物料编码"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        
        <el-form-item label="业务员">
          <el-select
            v-model="searchForm.salesperson"
            placeholder="输入员工姓名搜索"
            clearable
            filterable
            remote
            reserve-keyword
            :remote-method="handleEmployeeSearch"
            :loading="employeeLoading"
            style="width: 150px"
          >
            <el-option 
              v-for="employee in employeeOptions" 
              :key="employee.value" 
              :label="employee.label"
              :value="employee.value" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="客户名称">
          <el-input
            v-model="searchForm.customerName"
            placeholder="请输入客户名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="报价时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleSearch"
            :loading="loading"
          >
            <i class="fas fa-search"></i>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <i class="fas fa-redo"></i>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据列表区域 -->
    <el-card class="table-card" shadow="never">
      <!-- 操作按钮区 -->
      <div class="table-header">
        <div class="table-title">
          <i class="fas fa-list"></i>
          报价记录列表
        </div>
        <div class="table-actions">
          <el-button 
            type="success" 
            @click="handleCreateQuote"
          >
            <i class="fas fa-plus"></i>
            新增报价单
          </el-button>
          <el-button 
            type="warning" 
            @click="handleBatchOperation"
            :disabled="selectedRows.length === 0"
          >
            <i class="fas fa-edit"></i>
            批量操作
          </el-button>
          <el-button 
            type="info" 
            @click="handleExport"
          >
            <i class="fas fa-file-excel"></i>
            导出Excel
          </el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        class="quote-table"
      >
        <el-table-column type="selection" width="55" fixed="left" />
        
        <el-table-column 
          type="index" 
          label="序号" 
          width="70" 
          align="center"
          fixed="left"
        />
        
        <el-table-column 
          prop="quoteDate" 
          label="报价日期" 
          width="110"
          fixed="left"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="customerCode" 
          label="客户代码" 
          width="100"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="salesperson" 
          label="业务员" 
          width="90"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="isTaxIncluded" 
          label="是否含税" 
          width="90"
          align="center"
        >
          <template #default="{ row }">
            <el-tag 
              :type="row.isTaxIncluded === 1 ? 'success' : 'info'"
              size="small"
            >
              {{ row.isTaxIncluded === 1 ? '含税13%' : '不含税' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="orderArea" 
          label="订单面积" 
          width="100"
          align="right"
        >
          <template #default="{ row }">
            {{ row.orderArea ? `${row.orderArea}mm²` : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="pricePerSqm" 
          label="平米价" 
          width="100"
          align="right"
        >
          <template #default="{ row }">
            {{ row.pricePerSqm ? `¥${row.pricePerSqm}` : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="productName" 
          label="产品名称" 
          width="150"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="materialCode" 
          label="物料编码" 
          width="120"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="purchaseOrderNumber" 
          label="采购订单号" 
          width="130"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="layerCount" 
          label="层数" 
          width="70"
          align="center"
        />
        
        <el-table-column 
          prop="boardThickness" 
          label="板厚" 
          width="80"
          align="center"
        >
          <template #default="{ row }">
            {{ row.boardThickness ? `${row.boardThickness}mm` : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="surfaceTreatment" 
          label="表面处理" 
          width="100"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="solderMask" 
          label="阻焊" 
          width="80"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="silkscreen" 
          label="字符" 
          width="80"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="baseMaterial" 
          label="板材" 
          width="80"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="deliverySize" 
          label="交货尺寸(mm)" 
          width="120"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="panelization" 
          label="拼版" 
          width="80"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="innerCopper" 
          label="内铜" 
          width="80"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="outerCopper" 
          label="外铜" 
          width="80"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="viaProcess" 
          label="过孔工艺" 
          width="100"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="testing" 
          label="测试" 
          width="80"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="testFixtureFee" 
          label="测试架费" 
          width="100"
          align="right"
        >
          <template #default="{ row }">
            {{ row.testFixtureFee ? `¥${row.testFixtureFee}` : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="isUrgent" 
          label="加急" 
          width="70"
          align="center"
        >
          <template #default="{ row }">
            <el-tag 
              :type="row.isUrgent === '是' ? 'danger' : 'info'"
              size="small"
            >
              {{ row.isUrgent }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="quantity" 
          label="数量" 
          width="80"
          align="right"
        />
        
        <el-table-column 
          prop="unitPrice" 
          label="单价" 
          width="100"
          align="right"
        >
          <template #default="{ row }">
            {{ row.unitPrice ? `¥${row.unitPrice}` : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="sampleFee" 
          label="样板费" 
          width="100"
          align="right"
        >
          <template #default="{ row }">
            {{ row.sampleFee ? `¥${row.sampleFee}` : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="totalAmount" 
          label="合计金额" 
          width="120"
          align="right"
        >
          <template #default="{ row }">
            <span class="amount-text">
              {{ row.totalAmount ? `¥${row.totalAmount}` : '-' }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="deliveryDate" 
          label="出货日期" 
          width="110"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="remark" 
          label="备注" 
          width="150"
          show-overflow-tooltip
        />
        
        <el-table-column 
          label="操作" 
          width="200" 
          fixed="right"
          align="center"
        >
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              text
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              text
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              text
              @click="handleCopy(row)"
            >
              复制
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              text
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <div class="pagination-info">
          共 {{ total }} 条记录，当前第 {{ currentPage }}/{{ Math.ceil(total / pageSize) || 1 }} 页
        </div>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { 
  getQuoteRecords, 
  deleteQuote, 
  copyQuote, 
  approveQuote, 
  rejectQuote,
  getCustomerOptions,
  getEmployeeOptions,
  searchCustomers,
  searchEmployees
} from '@/api/quote'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const selectedRows = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const tableData = ref([])

// 搜索表单
const searchForm = reactive({
  customerCode: '',
  productName: '',
  materialCode: '',
  salesperson: '',
  customerName: '',
  dateRange: []
})

// 选项数据
const customerOptions = ref([])
const employeeOptions = ref([])

// 搜索状态
const customerLoading = ref(false)
const employeeLoading = ref(false)

// 计算属性
const searchParams = computed(() => {
  const params = {
    page: currentPage.value,
    size: pageSize.value
  }
  
  // 添加搜索条件
  if (searchForm.customerCode) {
    params.customerCode = searchForm.customerCode
  }
  
  if (searchForm.customerName) {
    params.customerName = searchForm.customerName
  }
  
  if (searchForm.salesperson) {
    params.salesperson = searchForm.salesperson
  }
  
  if (searchForm.productName) {
    params.productName = searchForm.productName
  }
  
  if (searchForm.materialCode) {
    params.materialCode = searchForm.materialCode
  }
  
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    params.startDate = searchForm.dateRange[0]
    params.endDate = searchForm.dateRange[1]
  }
  
  return params
})

// 客户搜索方法
const handleCustomerSearch = async (query) => {
  if (!query || query.trim() === '') {
    await loadCustomerOptions()
    return
  }
  
  customerLoading.value = true
  try {
    const response = await searchCustomers(query.trim())
    if (response.code === 200 && response.data) {
      if (response.data.records) {
        customerOptions.value = response.data.records.map(item => ({
          value: item.customerCode,
          label: item.customerName
        }))
      } else if (Array.isArray(response.data)) {
        customerOptions.value = response.data.map(item => ({
          value: item.customerCode,
          label: item.customerName
        }))
      }
    }
  } catch (error) {
    console.error('搜索客户失败:', error)
    ElMessage.error('搜索客户失败')
  } finally {
    customerLoading.value = false
  }
}

// 员工搜索方法
const handleEmployeeSearch = async (query) => {
  if (!query || query.trim() === '') {
    await loadEmployeeOptions()
    return
  }
  
  employeeLoading.value = true
  try {
    const response = await searchEmployees(query.trim())
    if (response.code === 200 && response.data) {
      if (response.data.records) {
        employeeOptions.value = response.data.records.map(item => ({
          value: item.employeeName,
          label: item.employeeName
        }))
      } else if (Array.isArray(response.data)) {
        employeeOptions.value = response.data.map(item => ({
          value: item.employeeName,
          label: item.employeeName
        }))
      }
    }
  } catch (error) {
    console.error('搜索员工失败:', error)
    ElMessage.error('搜索员工失败')
  } finally {
    employeeLoading.value = false
  }
}

// 事件处理函数
const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

const handleReset = () => {
  // 重置搜索表单
  Object.keys(searchForm).forEach(key => {
    if (Array.isArray(searchForm[key])) {
      searchForm[key] = []
    } else {
      searchForm[key] = ''
    }
  })
  
  // 重新加载数据
  currentPage.value = 1
  loadData()
  ElMessage.info('搜索条件已重置')
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleCreateQuote = () => {
  router.push('/order/quote')
}

const handleBatchOperation = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要操作的记录')
    return
  }
  
  ElMessage.info(`已选择 ${selectedRows.value.length} 条记录，批量操作功能开发中...`)
  // TODO: 实现批量操作功能
}

const handleExport = () => {
  ElMessage.info('导出功能开发中...')
  // TODO: 实现导出Excel功能
}

const handleView = (row) => {
  router.push(`/order/quote/view/${row.id}`)
}

const handleEdit = (row) => {
  // 只有草稿状态才能编辑
  if (row.status === 'DRAFT') {
    router.push(`/order/quote/edit/${row.id}`)
  } else {
    ElMessage.warning('只有草稿状态的报价单才能编辑')
  }
}

const handleCopy = async (row) => {
  try {
    const response = await copyQuote(row.id)
    if (response.code === 200) {
      ElMessage.success('复制成功')
      loadData() // 重新加载数据
    } else {
      ElMessage.error(response.message || '复制失败')
    }
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败，请稍后重试')
  }
}

const handleDelete = async (row) => {
  // 只有草稿状态才能删除
  if (row.status !== 'DRAFT') {
    ElMessage.warning('只有草稿状态的报价单才能删除')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除报价记录 "${row.productName}" 吗？此操作不可撤销。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteQuote(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadData() // 重新加载数据
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  loadData()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  loadData()
}

// 数据处理函数
const loadData = async () => {
  loading.value = true
  
  try {
    const response = await getQuoteRecords(searchParams.value)
    if (response.code === 200 && response.data) {
      if (response.data.records) {
        // 分页数据格式
        tableData.value = response.data.records
        total.value = response.data.total
      } else if (Array.isArray(response.data)) {
        // 数组格式
        tableData.value = response.data
        total.value = response.data.length
      }
    } else {
      ElMessage.error(response.message || '加载数据失败')
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败，请稍后重试')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 加载客户选项
const loadCustomerOptions = async (keyword = '') => {
  try {
    const response = await getCustomerOptions(keyword)
    if (response.code === 200 && response.data) {
      if (response.data.records) {
        customerOptions.value = response.data.records.map(item => ({
          value: item.customerCode,
          label: item.customerName
        }))
      } else if (Array.isArray(response.data)) {
        customerOptions.value = response.data.map(item => ({
          value: item.customerCode,
          label: item.customerName
        }))
      }
    }
  } catch (error) {
    console.error('加载客户选项失败:', error)
  }
}

// 加载员工选项
const loadEmployeeOptions = async (keyword = '') => {
  try {
    const response = await getEmployeeOptions(keyword)
    if (response.code === 200 && response.data) {
      if (response.data.records) {
        employeeOptions.value = response.data.records.map(item => ({
          value: item.employeeName,
          label: item.employeeName
        }))
      } else if (Array.isArray(response.data)) {
        employeeOptions.value = response.data.map(item => ({
          value: item.employeeName,
          label: item.employeeName
        }))
      }
    }
  } catch (error) {
    console.error('加载员工选项失败:', error)
  }
}

// 加载基础数据
const loadBaseData = async () => {
  try {
    // 并行加载客户和员工数据
    await Promise.all([
      loadCustomerOptions(),
      loadEmployeeOptions()
    ])
  } catch (error) {
    console.error('加载基础数据失败:', error)
  }
}

// 页面初始化
onMounted(async () => {
  await loadBaseData()
  loadData()
})
</script>

<style scoped>
.quote-record-container {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.search-card {
  border-radius: 6px;
  flex-shrink: 0;
}

.search-card :deep(.el-card__body) {
  padding: 16px;
}

.search-form {
  margin-bottom: 0;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 12px;
  margin-right: 16px;
}

.table-card {
  border-radius: 6px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-card :deep(.el-card__body) {
  padding: 16px;
  display: flex;
  flex-direction: column;
  flex: 1;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  display: flex;
  align-items: center;
}

.table-title i {
  margin-right: 8px;
  color: #409eff;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.quote-table {
  flex: 1;
  border-radius: 6px;
  overflow: hidden;
}

.quote-table :deep(.el-table th) {
  background-color: #fafafa;
  font-weight: 600;
  color: #333;
}

.quote-table :deep(.el-table--border) {
  border: 1px solid #ebeef5;
}

.amount-text {
  font-weight: 600;
  color: #409eff;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form :deep(.el-form-item) {
    width: 100%;
    margin-right: 0;
  }
  
  .table-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .table-actions {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .pagination-container {
    flex-direction: column;
    gap: 12px;
    align-items: center;
  }
}

/* 优化表格在小屏幕上的显示 */
@media (max-width: 1200px) {
  .quote-table :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }
}

/* 优化按钮样式 */
.el-button {
  border-radius: 4px;
  font-weight: 500;
}

.el-button i {
  margin-right: 4px;
}

/* 优化表单样式 */
.search-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 优化选择器和输入框样式 */
.search-form :deep(.el-input__wrapper),
.search-form :deep(.el-select .el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.search-form :deep(.el-input__wrapper:hover),
.search-form :deep(.el-select .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

.search-form :deep(.el-input__wrapper.is-focus),
.search-form :deep(.el-select .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}
</style> 